package cn.lyjuan.archetypes.bms.web.util;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class AppUtils
{
    private static Logger log = LogManager.getLogger(AppUtils.class);

    /**
     * 将对象解析为JSON并响应
     *
     * @param object
     */
    public static void respJson(Object object)
    {
        String json = JsonUtils.to(object);

        resp(json);
    }

    /**
     * 返回 Ajax 请求响应
     *
     * @param json 返回的JSON数据
     * @throws IOException
     */
    public static void resp(String json)
    {
        // 获取输出封装流
        PrintWriter out = null;
        try
        {
            out = res().getWriter();

            // 返回信息
            if (log.isDebugEnabled())
                log.debug("response >> " + json);

            out.write(json);
            out.flush();
        } catch (IOException e)
        {
            log.error("response json stream error", e);
        }
    }

    /**
     * 是否ajax请求
     */
    public static boolean isAjax()
    {
        HttpServletRequest req = req();

        if ("XMLHttpRequest".equalsIgnoreCase(req.getHeader("X-Requested-With"))
                || req.getParameter("ajax") != null || req.getHeader("ajax") == "true")
        {
            return true;
        }

        if (req.getRequestURI().indexOf("/api/") > -1) return true;

        return false;
    }

    /**
     * 获取 HttpServletRequest
     *
     * @return
     */
    public static HttpServletRequest req()
    {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    /**
     * 获取 HttpServletResponse
     *
     * @return
     */
    public static HttpServletResponse res()
    {
        HttpServletResponse resp = ((ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes()).getResponse();
        return resp;
    }
}
